const express = require('express')
const app = express()
const path = require('path')
const sqlite3 = require('sqlite3').verbose()
const bp = require('body-parser')
const _ = require('lodash')
const config = require('./config/config.json')

app.use(bp.json())
app.use(bp.urlencoded({
    extended: true
}));
let db = new sqlite3.Database('sndpjs.d')
// 初始化数据库
db.serialize(function () {
    db.run(`CREATE TABLE IF NOT EXISTS d (${config.database.join(',')})`);
})
// db.close();
app.post('/', (req, res) => {
    let data = Object.assign({}, req.body)
    data.ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress
    let values = _(data).toPairs().sortBy(0).fromPairs().value()
    let keys = _.keys(data).sort(0)
    // 写入数据
    db.serialize(function () {
        let stmt = db.prepare(`INSERT INTO d (${keys.join(',')}) VALUES (${(new Array(keys.length)).fill('?').join(',')})`)
        stmt.run.apply(stmt, _.values(values))
        stmt.finalize();
    })
    res.send({});
})

app.get('/_', (req, res) => {
    if (!req.query.t) {
        res.sendStatus(401)
        return
    }
    if (req.query.t === '') {
        res.sendStatus(401)
        return
    }
    if (req.query.t.length < 13) {
        res.sendStatus(401)
        return
    }
    if (parseInt(req.query.t).toString().length < 13) {
        res.sendStatus(401)
        return
    }
    let data = []
    db.serialize(function () {
        db.each(`SELECT * FROM d WHERE date>=${req.query.t} limit 0,100`, (err, row) => {
            data.push(row)
        }, () => {
            res.send(data)
        })
    })
})

app.use('/', express.static(path.join(__dirname, 'static')))

app.listen(config.port || 3000)
console.log('Server listen on port', config.port || 3000)

// 捕捉异常/信号等 
process.stdin.resume(); // 防止直接结束

function exitHandler(options, err) {
    db.close();
    if (options.cleanup) console.log('clean');
    if (err) console.log(err.stack);
    if (options.exit) process.exit();
}

// 关闭事件
process.on('exit', exitHandler.bind(null, {
    cleanup: true
}));

// Ctrl-C 事件
process.on('SIGINT', exitHandler.bind(null, {
    exit: true
}));

// 未知错误
process.on('uncaughtException', exitHandler.bind(null, {
    exit: true
}));